<template>
  <view class="setting-page">
    <!-- 设备号输入区域（输入框 + 提交按钮同一行） -->
    <text class="label">设备号：</text>
    <view class="form-row">
      <input class="input-box" :class="{ active: focusNavigator.getCurrentIndex() === 0 }" type="text"
        placeholder="请输入设备号" placeholder-style="color:#999" v-model="deviceNo" cursor-color="#ddd" tabindex="-1"
        :disabled="focusNavigator.getCurrentIndex() !== 0" @focus="handleInputFocus('device')"
        @blur="handleInputBlur" />
      <button class="submit-btn" :class="{ active: focusNavigator.getCurrentIndex() === 1 }" @click="eqCodeSubmit"
        tabindex="-1">提交</button>
    </view>

    <!-- 服务器地址修改区域（输入框 + 提交按钮同一行） -->
    <text class="label">服务器地址：</text>
    <view class="form-row">
      <input class="input-box" :class="{ active: focusNavigator.getCurrentIndex() === 2 }" type="text"
        placeholder="请输入服务器地址" placeholder-style="color:#999" v-model="newUrl" cursor-color="#ddd" tabindex="-1"
        :disabled="focusNavigator.getCurrentIndex() !== 2" @focus="handleInputFocus('server')"
        @blur="handleInputBlur" />
      <button class="submit-btn" :class="{ active: focusNavigator.getCurrentIndex() === 3 }" @click="serverAddrSubmit"
        tabindex="-1">修改</button>
    </view>

    <!-- 触发通知的按钮 -->
    <view class="button-group">
      <button class="action-btn" :class="{ active: focusNavigator.getCurrentIndex() === 4 }" @click="showNotification"
        tabindex="-1">点击发送通知</button>
      <button class="action-btn" :class="{ active: focusNavigator.getCurrentIndex() === 5 }" @click="fetchLocation"
        tabindex="-1">点击获取位置</button>
      <!-- <button class="action-btn test-btn" :class="{ active: focusNavigator.getCurrentIndex() === 6 }"
        @click="navigateToRing" tabindex="-1">更换通知铃声</button>
      <button class="action-btn test-btn" :class="{ active: focusNavigator.getCurrentIndex() === 7 }"
        @click="navigateToKey" tabindex="-1">按键映射测试</button> -->
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    onUnmounted,
    nextTick
  } from 'vue'
  import {
    onLoad,
    onShow,
    onHide,
  } from '@dcloudio/uni-app'
  import {
    createFocusNavigator
  } from '../../utils/key.js'

  // 通知示例
  import {
    createNotification,
    showNotification,
    testNotification
  } from '../../utils/notification.js'
  // 获取定位示例
  import {
    getLocationInfo
  } from '../../utils/locationUtils.js'

  const locationInfo = ref(null)
  const deviceNo = ref('')
  const newUrl = '61.27.43.30:10546/api'
  // 防重复弹窗标记
  const dialogInProgress = ref(false)
  // 弹窗关闭后的按键抑制时间，避免穿透/抖动
  let suppressKeysUntilTs = 0

  // 定义可聚焦项目列表 - 保持现有UI布局的索引顺序
  const focusItems = ref([{
      name: '设备号输入框',
      // onSelect: () => {
      //   // 焦点移动到这里时，直接拉起软键盘
      //   focusInput('device');
      // }
    },
    {
      name: '设备号提交',
      onSelect: () => eqCodeSubmit()
    },
    {
      name: '服务器地址输入框',
      // onSelect: () => {
      //   // 焦点移动到这里时，直接拉起软键盘
      //   focusInput('server');
      // }
    },
    {
      name: '服务器地址修改',
      onSelect: () => serverAddrSubmit()
    },
    {
      name: '发送通知',
      onSelect: () => showNotification()
    },
    {
      name: '获取位置',
      onSelect: () => fetchLocation()
    },
    {
      name: '更换铃声',
      onSelect: () => navigateToRing()
    },
    {
      name: '按键映射测试',
      onSelect: () => navigateToKey()
    }
  ]);

  // 创建焦点导航器
  const focusNavigator = createFocusNavigator(focusItems.value, 0);

  // 输入框聚焦函数（通过选择器精准获取 DOM）
  const focusInput = (type) => {
    nextTick(() => {
      const query = uni.createSelectorQuery().in(uni.getCurrentInstance());
      let selector = '';
      if (type === 'device') {
        selector = '.input-box[placeholder="请输入设备号"]';
      } else if (type === 'server') {
        selector = '.input-box[placeholder="请输入服务器地址"]';
      }
      query.select(selector).boundingClientRect((rect) => {
        if (rect) {
          // 拉起软键盘
          uni.showKeyboard();
          // 聚焦输入框（H5/APP 兼容）
          uni.createSelectorQuery()
            .in(uni.getCurrentInstance())
            .select(selector)
            .node((res) => {
              if (res.node) {
                res.node.focus();
              }
            })
            .exec();
        }
      }).exec();
    });
  };

  // 处理输入框聚焦事件（备用，主要靠 focusNavigator.onSelect 触发）
  const handleInputFocus = (type) => {
    console.log('输入框聚焦事件触发:', type);
    // 这里可加额外逻辑，比如记录聚焦状态
  };

  // 处理输入框失去焦点事件
  const handleInputBlur = () => {
    console.log('输入框失去焦点');
    // 收起软键盘
    uni.hideKeyboard();
  };

  // 监听焦点变化，处理输入框外的焦点移动
  const handleFocusChange = (newIndex) => {
    console.log('焦点移动到索引:', newIndex);

    // 如果焦点离开输入框，收起软键盘
    if (newIndex !== 0 && newIndex !== 2) {
      uni.hideKeyboard();
    }
  };

  // 重写焦点导航器的移动方法，添加焦点变化监听
  const originalMoveToNext = focusNavigator.moveToNext;
  const originalMoveToPrevious = focusNavigator.moveToPrevious;

  focusNavigator.moveToNext = () => {
    const currentIndex = focusNavigator.getCurrentIndex();
    originalMoveToNext.call(focusNavigator);
    const newIndex = focusNavigator.getCurrentIndex();
    if (newIndex !== currentIndex) {
      handleFocusChange(newIndex);
    }
  };

  focusNavigator.moveToPrevious = () => {
    const currentIndex = focusNavigator.getCurrentIndex();
    originalMoveToPrevious.call(focusNavigator);
    const newIndex = focusNavigator.getCurrentIndex();
    if (newIndex !== currentIndex) {
      handleFocusChange(newIndex);
    }
  };

  // 重写确认键逻辑：触发当前焦点的 onSelect
  focusNavigator.handleConfirm = () => {
    const currentItem = focusItems.value[focusNavigator.getCurrentIndex()];
    if (currentItem && currentItem.onSelect) {
      currentItem.onSelect();
    }
  };

  onLoad(() => {
    const savedDeviceNo = uni.getStorageSync('deviceNo');
    if (savedDeviceNo) deviceNo.value = savedDeviceNo;
    const baseUrl = uni.getStorageSync('baseUrl');
    if (baseUrl) newUrl.value = baseUrl;
  });

  let keyDownHandler = null
  let keyUpHandler = null

  const registerKeyHandlers = () => {
    const sys = uni.getSystemInfoSync();
    if (sys.platform !== 'android') return;
    if (keyDownHandler || keyUpHandler) {
      try {
        plus.key.removeEventListener('keydown', keyDownHandler);
      } catch (e) {}
      try {
        plus.key.removeEventListener('keyup', keyUpHandler);
      } catch (e) {}
    }
    keyDownHandler = (event) => {
      // 系统弹窗打开期间，完全让原生处理（左右切换按钮、BACK关闭等）
      if (dialogInProgress.value) return;
      // 页面级：上下移动焦点，确认触发当前项
      focusNavigator.handleKeyDown(event);
      if (event.keyCode === 23) {
        focusNavigator.handleConfirm();
      }
    };
    keyUpHandler = (event) => {
      if (dialogInProgress.value) return;
      focusNavigator.handleKeyUp(event);
    };
    plus.key.addEventListener('keydown', keyDownHandler);
    plus.key.addEventListener('keyup', keyUpHandler);
  };

  const unregisterKeyHandlers = () => {
    const sys = uni.getSystemInfoSync();
    if (sys.platform !== 'android') return;
    if (keyDownHandler) {
      try {
        plus.key.removeEventListener('keydown', keyDownHandler);
      } catch (e) {}
      keyDownHandler = null;
    }
    if (keyUpHandler) {
      try {
        plus.key.removeEventListener('keyup', keyUpHandler);
      } catch (e) {}
      keyUpHandler = null;
    }
  };

  onMounted(() => {
    console.log('Setting页面挂载完成，当前焦点索引:', focusNavigator.getCurrentIndex());
    console.log('可聚焦项目数量:', focusItems.value.length);
    console.log('项目列表:', focusItems.value.map((item, idx) => `${idx}: ${item.name}`));

    // 注册按键事件监听器（安卓）
    registerKeyHandlers();
  });

  onShow(() => {
    console.log('Setting页面重新显示，重新注册按键事件');
    registerKeyHandlers();
  });

  onHide(() => {
    unregisterKeyHandlers();
  });

  onUnmounted(() => {
    // 注销按键事件监听器
    unregisterKeyHandlers();
    // 清理焦点导航器
    focusNavigator.destroy();
  });

  // 设备号提交
  const eqCodeSubmit = () => {
    uni.setStorageSync('deviceNo', deviceNo.value);
    uni.showToast({
      title: '设备号已保存，重启后生效',
      icon: 'none',
      duration: 2000
    });
  };

  // 服务器地址提交
  const serverAddrSubmit = () => {
    uni.setStorageSync('baseUrl', newUrl.value);
    uni.showToast({
      title: '服务器地址已修改，重启后生效',
      icon: 'none',
      duration: 2000
    });
  };

  // 获取位置
  const fetchLocation = () => {
    console.log('用户点击了获取位置按钮');
    uni.showLoading({
      title: '获取位置中...',
      mask: true
    });
    getLocationInfo((result) => {
      uni.hideLoading();
      if (result.success) {
        locationInfo.value = result.data;
        console.log('位置信息获取成功:', result.data);
        if (plus.os.name === 'Android') {
          uni.showToast({
            title: '位置获取成功，请查看控制台日志',
            icon: 'success',
            duration: 3000
          });
        }
        showLocationPopup();
      } else {
        console.log('位置获取失败:', result.message);
        uni.showToast({
          title: result.message,
          icon: "none",
          duration: 3000
        });
      }
    });
  };

  // 弹窗展示位置信息
  const showLocationPopup = () => {
    const {
      latitude,
      longitude,
      city,
      district,
      street,
      address
    } = locationInfo.value;
    const locationText = `
    经纬度：
    ${latitude}, ${longitude}
    
    位置信息：
    ${city || ''}${district || ''}${street || ''}
    ${address || ''}
  `.trim();
    uni.showModal({
      title: "当前位置",
      content: locationText,
      showCancel: false,
      confirmText: "确定"
    });
  };

  // 跳转铃声设置
  const navigateToRing = () => {
    uni.navigateTo({
      url: '/pages/Setting/RingSetting/RingSetting'
    });
  };

  // 跳转按键映射测试
  const navigateToKey = () => {
    uni.navigateTo({
      url: '/pages/Setting/KeySetting/KeySetting'
    });
  };
</script>

<style lang="scss" scoped>
  .setting-page {
    padding: 32rpx;
    background-color: #555;
    min-height: 100vh;
  }

  .form-row {
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    margin-bottom: 30rpx;
    width: 100%;
    gap: 16rpx;
  }

  .label {
    font-size: 48rpx;
    color: #ddd;
    white-space: nowrap;
    width: 200rpx;
  }

  .input-box {
    flex: 1;
    height: 80rpx;
    border: 1px solid #ccc;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 36rpx;
    color: #ddd;
    background-color: #666;
  }

  .input-box:disabled {
    background-color: #444;
    color: #999;
    cursor: not-allowed;
  }

  .input-box.active {
    background-color: #007bff !important;
    color: white !important;
    border-color: #007bff;
  }

  .submit-btn {
    width: 160rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #4CAF50;
    color: #fff;
    font-size: 42rpx;
    border-radius: 8rpx;
    margin: 0;
  }

  .button-group {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin-top: 30rpx;
    gap: 16rpx;
  }

  .action-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #4CAF50;
    color: #fff;
    font-size: 42rpx;
    border-radius: 8rpx;
  }

  .test-btn {
    background-color: #4CAF50;
  }

  .active {
    background-color: #007bff !important;
    color: white !important;
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
  }

  *:focus {
    outline: none !important;
    box-shadow: none !important;
  }

  [tabindex="-1"]:focus {
    outline: none !important;
    box-shadow: none !important;
  }
</style>